package table.model;

import javax.swing.table.AbstractTableModel;

import table.MultiLineTable;
import table.model.rowModel.Row;
import table.model.rowModel.SortedRowModel;
import table.view.multirowheader.GroupableTableColumnModel;

/**
 * 
 * @author dernasherbrezon
 *
 */
public class BasicModel extends AbstractTableModel
{
	AbstractTableModel userDataModel;
	MultiLineTable table;
	
	//FIXME
	GroupableTableColumnModel columnModel;
	SortedRowModel rowModel;
	
	public BasicModel(MultiLineTable table,AbstractTableModel userDataModel) {
		this.userDataModel = userDataModel;
		this.table = table;
	}
	
	public void setColumnModel(GroupableTableColumnModel columnModel) {
		this.columnModel = columnModel;
	}
	
	public void setRowModel(SortedRowModel rowModel) {
		this.rowModel = rowModel;
	}
	
	public int getRowCount() {
		return userDataModel.getRowCount();
	}

	public int getColumnCount() {
		if(columnModel!=null) {
			return columnModel.getColumnCount();
		}
		return 0;
	}

	public Object getValueAt(int row, int col) {
		SimpleColumn curColumn = columnModel.getColumn(col);
		Row curRow = rowModel.getRow(row);
		
		String retValue = ""; 
		if (curColumn instanceof ComplexColumn) {
			for(int i=0;i<((ComplexColumn)curColumn).childs.size();i++) {
				int curIndex = ((ComplexColumn)curColumn).childs.get(i).realModelIndex;
				if(i!=0) {
					retValue+="\n";
				}
				retValue += userDataModel.getValueAt(curRow.getModelIndex(),curIndex);
			}
		}
		else {
			retValue+=userDataModel.getValueAt(curRow.getModelIndex(),curColumn.realModelIndex);
		}
		return retValue;
	}
	
	public void fireChanged() {
		super.fireTableDataChanged();
		super.fireTableStructureChanged();
	}
	
	@Override
	public boolean isCellEditable(int rowIndex, int columnIndex) {
		SimpleColumn curColumn = columnModel.getColumn(columnIndex);
		//TODO unknown actions
		if (curColumn instanceof ComplexColumn) {
			return false;
		}
		return userDataModel.isCellEditable(rowIndex, columnIndex);
	}
	
	@Override
	public void setValueAt(Object aValue, int row, int col) {
		SimpleColumn curColumn = columnModel.getColumn(col);
		Row curRow = rowModel.getRow(row);
		userDataModel.setValueAt(aValue, curRow.getModelIndex(),curColumn.realModelIndex);
	}
}
